<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Search, Delete, Edit } from '@element-plus/icons-vue'
import axios from '@/utils/axios'
import { dateFormat } from '@/hooks/Tools'
import Add from '@/components/admin/Add.vue'
import 'element-plus/es/components/message/style/css'
import 'element-plus/es/components/message-box/style/css'
import adminEdit from '@/components/admin/Edit.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 表格数据
let tableData = ref([] as any)
// 当前页
let page = ref(1)
// 每页显示条数
let pagesize = ref(10)
// 搜索关键词
let username = ref('')
// 总记录数
let total = ref(0)
// 分页偏移量
let pageOffset = ref(0)
// 选中的数据
let selectedData = ref([] as any)
// 添加弹层开关
let addFormVisible = ref(false)
let editFormVisible = ref(false)
// 编辑的数据
// let editData = reactive({} as { id: number, username: string})
let editData = reactive({} as AdminType)
//定义类型接口
interface AdminType {
    id: number,
    username: string
}
// 获取表格数据
async function getTableData() {
    const { code, offset, count, data }: any = await axios.get('/admin', {
        params: {
            page: page.value,
            pagesize: pagesize.value,
            username: username.value,
        }
    })
    if (code === 0) {
        tableData.value = data
        pageOffset.value = offset
        total.value = count
    }
}
// 搜索
function search() {
    page.value = 1
    pageOffset.value = 0
    getTableData()
}
// 多选
function handleSelectionChange(value: any[]) {
    selectedData.value = value;
}
// 激活禁用
async function active(id: number, active: number) {
    const { code, message }: any = await axios.put(`/admin/${id}/active/${active}`)
    if (code === 0) {
        ElMessage.success(message)
    } else {
        ElMessage.error(message)
    }
}
// 编辑
function edit(id: number, username: string) {
    editData.id = id
    editData.username = username
}
// 删除
function del(id: number) {
    ElMessageBox.confirm('此操作将永久删除该管理员信息,是否继续?', '删除提示', {
        type: 'warning',
    }).then(async () => {
        const { code, message }: any = await axios.delete(`/admin/${id}`)
        if (code === 0) {
            ElMessage.success(message)
            // 从表格中删除当前已被删除数据
            tableData.value = tableData.value.filter((item: any) => item.id != id)
        } else {
            ElMessage.error(message)
        }
    }).catch(() => { })
}
// 批量删除
function dels() {
    ElMessageBox.confirm('此操作将永久删除这些管理员信息,是否继续?', '批量删除提示', {
        type: 'warning',
    }).then(async () => {
        // 获取要删除的数据的id所组成的数组, []
        const ids: number[] = []
        selectedData.value.forEach((item: any) => ids.push(item.id))
        const { code, message }: any = await axios.delete('/admin', { data: { ids } })
        if (code === 0) {
            ElMessage.success(message)
            // 从表格中删除当前已被删除数据
            tableData.value = tableData.value.filter((item: any) => !ids.includes(item.id))
        } else {
            ElMessage.error(message)
        }
    }).catch(() => { })
}

// 切换每页显示条数
function handleSizeChange(value: number) {
    pagesize.value = value
    getTableData()
}
// 切换当前页
function handleCurrentChange(value: number) {
    page.value = value
    getTableData()
}

// 处理添加成功
function handleAddSuccess(data: any) {
    // 显示新增
    tableData.value.unshift(data)
    // 关闭添加弹窗
    addFormVisible.value = false
}

// 初始化数据
onMounted(() => {
    getTableData()
})
</script>

<template>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/bg' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>管理员管理</el-breadcrumb-item>
        <el-breadcrumb-item>管理员列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 功能区域 -->
    <el-card>
        <el-row :gutter="60">
            <el-col :span="10">
                <el-input placeholder="请输入内容" v-model="username" class="input-with-select">
                    <template #append>
                        <el-button :icon="Search" @click="search" />
                    </template>
                </el-input>
            </el-col>
            <el-col :span="3">
                <el-button type="primary" @click="addFormVisible = true">添加管理员</el-button>
            </el-col>
            <el-col :span="3">
                <el-button type="danger" @click="dels">批量删除</el-button>
            </el-col>
        </el-row>
        <el-table :data="tableData" height="480px" @selection-change="handleSelectionChange" stripe border>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="编号" width="80" align="center">
                <template #default="scope">
                    {{ scope.$index + 1 + pageOffset }}
                </template>
            </el-table-column>
            <el-table-column label="管理员名称" prop="username"></el-table-column>
            <el-table-column prop="create_time" :formatter="dateFormat" label="添加时间">
            </el-table-column>
            <el-table-column label="状态" align="center">
                <template #default="scope">
                    <el-switch @change="active(scope.row.id, scope.row.active)" v-model="scope.row.active"
                        :active-value="1" :inactive-value="2" active-color="#13ce66" inactive-color="#ff4949">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="登录次数" prop="login_num" align="center">
            </el-table-column>
            <el-table-column label="最近一次登录" prop="login_time" :formatter="dateFormat">
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="warning" title="修改密码"
                        @click="edit(scope.row.id, scope.row.username), editFormVisible = true" size="small"
                        :icon="Edit"></el-button>
                    <el-button type="danger" @click="del(scope.row.id)" title="删除" size="small" :icon="Delete">
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
            :page-sizes="[3, 5, 10, 50]" :page-size="pagesize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
    </el-card>
    <!-- 添加管理员弹层 -->
    <el-dialog title="添加管理员" v-model="addFormVisible">
        <Add @cancle="addFormVisible = false" @addSuccess="handleAddSuccess" v-if="addFormVisible"></Add>
    </el-dialog>
    <!-- 修改管理员密码弹层 -->
    <el-dialog title="修改管理员密码" v-model="editFormVisible">
        <adminEdit @cancle="editFormVisible = false" :id="editData.id" :username="editData.username"
            @editSuccess="editFormVisible = false" v-if="editFormVisible"></adminEdit>
    </el-dialog>
</template>

